<template>
  <div class="container">
    <el-drawer v-model="drawer" :size="size">
      <template #header>
        <h2>详情</h2>
      </template>
      <template #default>
        <div>
          <el-descriptions :title="dataForm.uname + '会员详情'" border>
            <el-descriptions-item label="用户操作" :span="3">
              <el-button-group size="small">
                <el-button type="primary" plain :icon="Wallet" v-if="hasPermission('member:member:balance')" @click="moreCommandHandle('updateBalance', dataForm.id)">账户余额</el-button>
                <el-button type="primary" plain :icon="User" v-if="hasPermission('member:member:status')" @click="moreCommandHandle('updateStatus', dataForm.id)">账户状态</el-button>
                <el-button type="primary" plain :icon="Flag" @click="moreCommandHandle('updateFlag', dataForm.id)">会员标签</el-button>
                <el-button type="primary" plain :icon="Lock" v-if="hasPermission('member:member:pwd')" @click="moreCommandHandle('updatePwd', dataForm.id)">账户密码</el-button>
                <el-button type="primary" plain :icon="User" @click="moreCommandHandle('updateTelegram', dataForm.id)">用户TG</el-button>
                <el-button type="primary" plain :icon="User" @click="moreCommandHandle('updateTelegramGroup', dataForm.id)">绑定社群</el-button>
                <el-button type="primary" plain :icon="Coin" v-if="hasPermission('member:member:pwd')" @click="moreCommandHandle('updateRate', dataForm.id)">费率设置</el-button>
                <el-button type="primary" plain :icon="Coin" @click="moreCommandHandle('pushNotice', dataForm.id)">消息推送</el-button>
              </el-button-group>
            </el-descriptions-item>
            <el-descriptions-item label="用户名">{{ dataForm.uname }}</el-descriptions-item>
            <el-descriptions-item label="获客渠道">{{ dataForm.channelCode }}</el-descriptions-item>
            <el-descriptions-item label="邀请人">
              <el-link type="primary" @click="memberDetailHandle(dataForm)">{{ dataForm.puname }}</el-link>
            </el-descriptions-item>
            <el-descriptions-item label="推荐码">{{ dataForm.referralCode }}</el-descriptions-item>
            <el-descriptions-item label="用户TG">
              <el-link type="primary" @click="openTgHandle(1, dataForm.telegram)">{{ dataForm.telegram || "-" }}</el-link>
            </el-descriptions-item>
            <el-descriptions-item label="所属社群">
              <el-link type="primary" @click="openTgHandle(2, dataForm.telegramGroup)">{{ dataForm.telegramGroup || "-" }}</el-link>
            </el-descriptions-item>
            <el-descriptions-item label="余额">{{ dataForm.balance }}</el-descriptions-item>
            <el-descriptions-item label="出售中">{{ dataForm.frozenBalance }}</el-descriptions-item>
            <el-descriptions-item label="任务赏金">{{ dataForm.bounty }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <dict-label dict-type="member_status" :dict-value="dataForm.status" :status="{ 2: 'warning', 3: 'danger' }"></dict-label>
            </el-descriptions-item>
            <el-descriptions-item label="标签">
              <div>
                <el-tooltip class="box-item" effect="dark" :content="item.name" placement="top-start" v-for="(item, index) in matchTags(dataForm.flagIds)" :key="index">
                  <svg class="iconfont" aria-hidden="true" :color="item.paramJsonObj?.color">
                    <use :xlink:href="`#${item.paramJsonObj?.icon}`"></use>
                  </svg>
                </el-tooltip>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-radio-group v-model="tab" style="margin-top: 30px" @change="tabHandle">
          <el-radio-button label="memberext">扩展信息</el-radio-button>
          <el-radio-button label="buyorder">充值订单</el-radio-button>
          <el-radio-button label="sellorder">卖出订单</el-radio-button>
          <el-radio-button label="accountchange">账变记录</el-radio-button>
          <el-radio-button label="paymentmethods">支付方式</el-radio-button>
          <el-radio-button label="loginlog">登录日志</el-radio-button>
        </el-radio-group>
        <div class="content">
          <template v-if="tab === 'memberext'">
            <memberext ref="memberextRef" />
          </template>
          <template v-if="tab === 'buyorder'">
            <buyorder ref="buyorderRef" />
          </template>
          <template v-if="tab === 'sellorder'">
            <sellorder ref="sellorderRef" />
          </template>
          <template v-if="tab === 'paymentmethods'">
            <paymentmethods ref="paymentmethodsRef" />
          </template>
          <template v-if="tab === 'loginlog'">
            <loginlog ref="loginlogRef" />
          </template>
          <template v-if="tab === 'accountchange'">
            <accountchange ref="accountchangeRef" />
          </template>
          <member-detail-drawer ref="memberDetailRef" :key="addKey" :sub="true"></member-detail-drawer>
        </div>
        <update-status ref="updateStatusRef" @refreshDataList="refreshDataListHandle"></update-status>
        <update-pwd ref="updatePwdRef" @refreshDataList="refreshDataListHandle"></update-pwd>
        <update-balance ref="updateBalanceRef" @refreshDataList="refreshDataListHandle"></update-balance>
        <update-flag ref="updateFlagRef" @refreshDataList="refreshDataListHandle"></update-flag>
        <update-remark ref="updateRemarkRef" @refreshDataList="refreshDataListHandle"></update-remark>
        <update-telegram ref="updateTelegramRef" @refreshDataList="refreshDataListHandle"></update-telegram>
        <update-telegram-group ref="updateTelegramGroupRef" @refreshDataList="refreshDataListHandle"></update-telegram-group>
        <update-rate ref="updateRateRef" @refreshDataList="refreshDataListHandle"></update-rate>
        <push-notice ref="pushNoticeRef" @refreshDataList="refreshDataListHandle"></push-notice>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="confirmClick">Close</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { checkPermission } from "@/utils/utils";
import { useAppStore } from "@/store";
import { Coin, Wallet, User, Lock, Flag } from "@element-plus/icons-vue";
import baseService from "@/service/baseService";
import buyorder from "./member-detail/buyorder.vue";
import sellorder from "./member-detail/sellorder.vue";
import memberext from "./member-detail/memberext.vue";
import paymentmethods from "./member-detail/paymentmethods.vue";
import loginlog from "./member-detail/loginlog.vue";
import accountchange from "./member-detail/accountchange.vue";
import MemberDetailDrawer from "@/views/member/member-detail-drawer.vue";
import UpdateStatus from "@/views/member/member-update-status.vue";
import UpdatePwd from "@/views/member/member-update-pwd.vue";
import UpdateBalance from "@/views/member/member-update-balance.vue";
import UpdateFlag from "@/views/member/member-update-flag.vue";
import UpdateRemark from "@/views/member/member-update-remark.vue";
import UpdateTelegram from "@/views/member/member-update-telegram.vue";
import UpdateTelegramGroup from "@/views/member/member-update-telegram-group.vue";
import UpdateRate from "@/views/member/member-update-rate.vue";
import PushNotice from "@/views/member/membernotice-add-or-update.vue";
const drawer = ref(false);
const tab = ref("memberext");
const emit = defineEmits(["refreshDataList"]);

const props = defineProps({
  sub: {
    type: Boolean,
    default: false
  }
});

const store = useAppStore();

const size: any = ref("80%");

const dataForm = reactive({
  id: "",
  uname: "",
  channelCode: "",
  referralCode: "",
  balance: "",
  bounty: "",
  commission: "",
  levelId: "",
  telegram: "",
  telegramGroup: "",
  frozenBalance: "",
  flagIds: "",
  status: 1,
  puname: ""
});

const flagIds = ref([]);

const init = (row?: any) => {
  drawer.value = true;

  if (props.sub) {
    nextTick(() => {
      size.value = 1400;
    });
  }

  if (row.memberId) {
    getInfo(row.memberId);
  }
};

// 获取信息
const getInfo = (id: number) => {
  getTags();
  baseService.get("/member/member/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    setTimeout(() => {
      tabHandle(tab.value);
    }, 200);
  });
};

const confirmClick = () => {
  drawer.value = false;
};

const hasPermission = (key: string) => {
  return checkPermission(store.state.permissions as string[], key);
};

const buyorderRef = ref("");
const sellorderRef = ref("");
const memberextRef = ref("");
const paymentmethodsRef = ref("");
const loginlogRef = ref("");
const accountchangeRef = ref("");
const tabHandle = async (val: string) => {
  const emeu: any = {
    buyorder: buyorderRef.value,
    sellorder: sellorderRef.value,
    memberext: memberextRef.value,
    paymentmethods: paymentmethodsRef.value,
    loginlog: loginlogRef.value,
    accountchange: accountchangeRef.value
  };
  await nextTick();
  emeu[val].init(dataForm);
};

const addKey = ref(0);
const memberDetailRef = ref();
const memberDetailHandle = (row?: any) => {
  let pid: any = "";
  if (row.pids) {
    let arr = row.pids.split(",");
    if (arr.length) {
      pid = arr[arr.length - 1];
    }
  }
  if (!+pid) return;

  addKey.value++;
  nextTick(() => {
    let info = {
      ...row,
      memberId: pid,
      sub: true
    };
    memberDetailRef.value.init(info);
  });
};

// 获取会员标签
const getTags = () => {
  baseService.get("/member/flag/all").then((res) => {
    flagIds.value = res.data;
  });
};

// 匹配会员标签
const matchTags = (ids: any) => {
  let flagids: any = [];
  if (ids) {
    try {
      let flag = JSON.parse(ids);
      if (flag !== 0) {
        flagids = flag;
      }
    } catch (error) {
      console.log(error);
    }
  }
  let result: any = flagIds.value.filter((item: any) => flagids.includes(item.id));
  return result;
};

const updateStatusRef = ref();
const updatePwdRef = ref();
const updateBalanceRef = ref();
const updateFlagRef = ref();
const updateRemarkRef = ref();
const updateRateRef = ref();
const pushNoticeRef = ref();
const updateTelegramRef = ref();
const updateTelegramGroupRef = ref();
const moreCommandHandle = (command: string, id?: string) => {
  nextTick(() => {
    if (command === "updateStatus") {
      updateStatusRef.value.init(id);
    }
    if (command === "updatePwd") {
      updatePwdRef.value.init(id);
    }
    if (command === "updateBalance") {
      updateBalanceRef.value.init(id);
    }
    if (command === "updateFlag") {
      updateFlagRef.value.init(id);
    }
    if (command === "updateTelegram") {
      updateTelegramRef.value.init(id);
    }
    if (command === "updateTelegramGroup") {
      updateTelegramGroupRef.value.init(id);
    }
    if (command === "updateRate") {
      updateRateRef.value.init(id);
    }
    if (command === "pushNotice") {
      pushNoticeRef.value.init("", id);
    }
  });
};

const openTgHandle = (type: any, value: any) => {
  if (!value) return;
  var istg = /t\.me/.test(value);
  if (istg) {
    window.open(`${value}`, "_blank", "width=500,height=500,toolbar=no");
  } else {
    if (value.includes("@")) {
      value = value.replace("@", "");
    }
    window.open(`https://t.me/${value}`, "_blank", "width=500,height=500,toolbar=no");
  }
};

const refreshDataListHandle = () => {
  emit("refreshDataList");
};

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
.container :deep(.el-drawer__header) {
  margin-bottom: 0;
}
.content {
  margin-top: 10px;
}
</style>
